package juc.blockqueue.priorityblockingqueue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * @ClassName TaskScheduler
 * @PackageName juc.blockqueue.priorityblockingqueue
 * @projectName myThread
 * @Description 1. 任务调度系统
 * @Author games
 * @Date 2025/9/4 上午11:31
 * @Version 1.0
 */
class PriorityTask implements Comparable<PriorityTask> {
    private final int priority;
    private final String taskName;
    private final long createTime;

    public PriorityTask(int priority, String taskName) {
        this.priority = priority;
        this.taskName = taskName;
        this.createTime = System.currentTimeMillis();
    }

    @Override
    public int compareTo(PriorityTask other) {
        // 优先级高的排在前面，优先级相同时按创建时间排序
        int result = Integer.compare(other.priority, this.priority);
        return result != 0 ? result : Long.compare(this.createTime, other.createTime);
    }

    // getters...
    public String getTaskName() { return taskName; }
    public int getPriority() { return priority; }
}

public class TaskScheduler {
    public static void main(String[] args) {
        BlockingQueue<PriorityTask> taskQueue = new PriorityBlockingQueue<>();

        // 添加不同优先级的任务
        new Thread(() -> {
            try {
                taskQueue.put(new PriorityTask(1, "Low Priority Task"));
                taskQueue.put(new PriorityTask(5, "High Priority Task"));
                taskQueue.put(new PriorityTask(3, "Medium Priority Task"));
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();

        // 任务执行器
        new Thread(() -> {
            try {
                while (true) {
                    PriorityTask task = taskQueue.take(); // 总是获取优先级最高的任务
                    System.out.println("Executing: " + task.getTaskName() +
                            " (Priority: " + task.getPriority() + ")");
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();
    }
}
